本文给出了Leetcode第8题的代码.

String to Integer (atoi)

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a
challenge, please do not see below and ask yourself what are the
possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no
given input specs). You are responsible to gather all the input
requirements up front.

这道题还是对于Integer的处理,在Reverse Integer这道题中我有提到,这种题的考察重点并不在于问题本身,而是要注意corner case的处理,整数一般有两点,一个是正负符号问题,另一个是整数越界问题。思路比较简单,就是先去掉多余的空格字符,然后读符号(注意正负号都有可能,也有可能没有符号),接下来按顺序读数字,结束条件有三种情况:(1)异常字符出现(按照C语言的标准是把异常字符起的后面全部截去,保留前面的部分作为结果);(2)数字越界(返回最接近的整数);(3)字符串结束。代码如下:
来自: http://blog.csdn.net/linhuanmars/article/details/21145129

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public int myAtoi(String str) {
if(str == null) return 0;
if(str.isEmpty()) return 0;
char[] s2ch = str.toCharArray();
int len = s2ch.length;
int res = 0;
boolean positive = true;
int i = 0;
while(s2ch[i] == ' '){
i++;
}
if(s2ch[i] != '+'){
if(s2ch[i] == '-')
positive = false;
else if(s2ch[i] < '0' || s2ch[i] > '9')
return 0;
else
res = s2ch[i] - '0';
}
i++;
for(;i < len;i++){
if(s2ch[i] < '0' || s2ch[i] > '9') break;
int digit = s2ch[i] - '0';
if(!positive && res>-((Integer.MIN_VALUE+digit)/10))
return Integer.MIN_VALUE;
else if(positive && res>(Integer.MAX_VALUE-digit)/10)
return Integer.MAX_VALUE;
res = 10*res + digit;
}
return positive ? res : -res;
}
本文总阅读量次.

留言